<template>
  <canvas ref="dom"></canvas>
</template>

<script setup lang="ts" name="SvgaAnimation">
import { Parser, Player } from 'svga'

const props = defineProps({
  status: {
    type: Boolean,
    default: false,
  },
  // svga资源
  name: {
    type: String,
    default: '',
  },
  isCacheFrames: {
    typeof: Boolean,
    default: true,
  }
})

const getPath = (name, status) => {
  return new URL(`../../assets/svga/${name}/${status}.svga`, import.meta.url).href;
}

const parser = new Parser();
const svgas = ref({});

const getParser = async () => {
  svgas.value = { static: await parser.load(getPath(props.name, '1.static')), move: await parser.load(getPath(props.name, '1.move')) }
}

const status = ref('static')

// 初始化
const dom = ref(null)
const player = ref(null)
const init = async () => {
  if (!props.name) return
  await nextTick()
  player.value = new Player({
    container: dom.value,
    startFrame: 0,
    loop: 0,
    isCacheFrames: props.isCacheFrames,
  })
  // 结束
  player.value.onEnd = async () => {
    if (status.value === 'static') {
      return;
    }
    switchState('static')
  }
  await mountPlaer()
  player.value.start()
}

const mountPlaer = async () => {
  await player.value.mount(svgas.value[status.value])
}

// 切换
const switchState = async (Status) => {
  player.value.clear()
  status.value = Status
  player.value.config.loop = Status === 'move' ? 1 : 0
  await mountPlaer()
  player.value.start()
}

watch(() => props.status, (v) => {
  switchState('move')
})

onMounted(async () => {
  await getParser()
  init()
})
</script>